/**
 *
 */
package com.cbwl.eoas.common.util;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.cbwl.eoas.common.framework.utils.ExceptionUtils;




/**
 * 时间工具类
 *
 * @author yyb
 *
 */
public class DateUtil
{
	
	
	private static Logger LOG = LoggerFactory.getLogger(DateUtil.class);
	
	/**
	 * <p>将字符串日期转换为Date</p>
	 */
	public static Date convertToDate(String s) {
		DateFormat df;
		if (StringUtils.isEmpty(s)) {
			return null;
		}
		if (s.contains("/")) {
			s = s.replaceAll("/", "-");
		}
		if (s.contains(":")) {
			try {
				df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				return df.parse(s);
			} catch (Exception e) {
				LOG.error(ExceptionUtils.getTrace(e));
			}
		} else {
			try {
				df = new SimpleDateFormat("yyyy-MM-dd");
				return df.parse(s);
			} catch (Exception e) {
				LOG.error(ExceptionUtils.getTrace(e));
			}
		}
		return null;
	}

	/**
	 * <p>将Date转换为String(格式：yyyy-MM-dd)</p>
	 */
	public static String formatDate(Date d) {
		if (d == null) {
			return null;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.format(d);
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getTrace(e));
		}

		return null;
	}

	/**
	 * 
	 * <p>将时间格式化为yyyy年 mm月dd日</p>
	 * 
	 * @param d
	 * @return
	 * @author: 虞云波 - yuyunbo@lawxp.com
	 * @date: Created on 2015-11-18 下午02:52:23
	 */
	public static String formatDateYMD(Date d) {
		if (d == null) {
			return null;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		try {
			return sdf.format(d);
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getTrace(e));
		}

		return null;
	}

	/**
	 * <p>获取当前时间戳</p>
	 */
	public static String getTimeStamp() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

		try {
			return sdf.format(new java.util.Date());
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getTrace(e));
		}

		return null;
	}

	/**
	 * <p>将Date转换为String(格式：yyyy-MM-dd HH:mm:ss)</p>
	 */
	public static String formatDateTime(Date d) {
		if (d == null) {
			return null;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		try {
			return sdf.format(d);
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getTrace(e));
		}

		return null;
	}

	/**
	 * <p>将Date转换为String(格式：yyyy-MM-dd HH:mm:ss)</p>
	 */
	public static String formatDateTime(Date d, String format) {
		if (d == null) {
			return null;
		}

		SimpleDateFormat sdf = new SimpleDateFormat(format);

		try {
			return sdf.format(d);
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getTrace(e));
		}

		return null;
	}

	/**
	 * <p>将Date按locale转换为String(格式：yyyy-MM-dd)</p>
	 */
	public static String formatLocaleDate(Date d, Locale locale) {
		if (d == null) {
			return null;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", locale);
		try {
			return sdf.format(d);
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getTrace(e));
		}

		return null;
	}

	/**
	 * <p>将Date按locale转换为String(格式：yyyy-MM-dd HH:mm:ss)</p>
	 */
	public static String formatLocaleDateTime(Date d, Locale locale) {
		if (d == null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", locale);
		try {
			return sdf.format(d);
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getTrace(e));
			return null;
		}
	}

	/**
	 * <p>得到每月多少天</p>
	 */
	public static int getDaysByMonth(int year, int month) {
		if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
			return 31;
		}

		if (month == 4 || month == 6 || month == 9 || month == 11){
			return 30;
		}
		if (month == 2) {
			if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
				return 29;
			} else {
				return 28;
			}
		}

		return -1;
	}

	/**
	 * <p>把星期的数字转换成汉字</p>
	 * 1：周日，2:周一.....7:周六
	 */
	public static String dayOfWeekByDayNum(int x) {
		String str = "星期日";
		if (x == 7) {
			str = "星期六";
		} else if (x == 6) {
			str = "星期五";
		} else if (x == 5) {
			str = "星期四";
		} else if (x == 4) {
			str = "星期三";
		} else if (x == 3) {
			str = "星期二";
		} else if (x == 2) {
			str = "星期一";
		}

		return str;
	}

	/**
	 * <p>据年、月、日，获得当天为周几，返回的是整数</p>
	 */
	public static int getWeekByDate(int year, int month, int day) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month - 1);
		c.set(Calendar.DAY_OF_MONTH, day);

		return c.get(Calendar.DAY_OF_WEEK);
	}

	/**
	 * <p>得到现在是这个周的第几天</p>
	 */
	public static int getWeekByDate() {
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.DAY_OF_WEEK);
	}

	/**
	 * <p>获取两个日期间的月份集合</p>
	 */
	public static List<String> monthDiff(Date date1, Date date2) throws Exception {
		List<String> monthList = new ArrayList<String>();

		if (DateUtil.dateDiff(date1, date2) < 0) {
			return monthList;
		}

		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		while (DateUtil.dateDiff(calendar1.getTime(), calendar2.getTime()) >= 0) {
			monthList.add(DateUtil.formatDate(calendar1.getTime()));
			calendar1.set(Calendar.DAY_OF_MONTH, 1);
			calendar1.set(Calendar.MONTH, calendar1.get(Calendar.MONTH) + 1);
		}
		if (monthList.size() > 0) {
			monthList.remove(monthList.size() - 1);
			monthList.add(DateUtil.formatDate(date2));
		}

		return monthList;
	}

	/**
	 * <p>时间比较</p>
	 * 
	 * date1 > date2   return 1
	 * date1 < date2   return -1
	 * date1 = date2   return 0
	 * @param date1
	 * @param date2
	 * @return
	 * @author: yuyunbo 
	 * @date: Created on 2014-12-21 下午03:26:48
	 */
	public static int compareDate(Date date1, Date date2) {
		if (date1.getTime() > date2.getTime()) {
			return 1;
		} else if (date1.getTime() < date2.getTime()) {
			return -1;
		} else {
			return 0;
		}
	}

	/**
	 * <p>计算两个日期之间相差多少秒</p>
	 * 
	 * @param date1 起始时间
	 * @param date2 终止时间
	 */
	public static int dateDiffSecond(final Date date1, final Date date2) throws Exception {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		long increaseDate = (calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) / 1000;
		// if (((calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) % (1000 * 60 * 60)) > 0) {
		// increaseDate = increaseDate + 1;
		// }
		return (int) increaseDate;
	}

	/**
	 * <p>计算两个日期之间相差多少毫秒</p>
	 * 
	 * @param date1 起始时间
	 * @param date2 终止时间
	 */
	public static long dateDiffMilliSecond(final Date date1, final Date date2) throws Exception {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		long increaseDate = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
		return increaseDate;
	}

	/**
	 * 
	 * <p>返回两个时间之间的秒数，保留6位小数</p>
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 * @throws Exception
	 * @author: 虞云波 - yuyunbo@lawxp.com
	 * @date: Created on 2016-7-9 下午12:25:47
	 */
	public static String dateDiffSecondStr(final Date date1, final Date date2) throws Exception {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		BigDecimal increaseDate = BigDecimalUtil.sub(calendar2.getTimeInMillis(), calendar1.getTimeInMillis(), 6);
		return BigDecimalUtil.div(increaseDate, 1000, 6).toString();
	}

	/**
	 * <p>计算两个日期之间相差多少分钟</p>
	 * 
	 * @param date1 起始时间
	 * @param date2 终止时间
	 */
	public static int dateDiffMinute(final Date date1, final Date date2) throws Exception {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		long increaseDate = (calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) / 1000 / 60;
		// if (((calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) % (1000 * 60 * 60)) > 0) {
		// increaseDate = increaseDate + 1;
		// }
		return (int) increaseDate;
	}

	/**
	 * <p>计算两个日期之间相差多少小时</p>
	 * 
	 * @param date1 起始时间
	 * @param date2 终止时间
	 */
	public static int dateDiffHour(final Date date1, final Date date2) throws Exception {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		long increaseDate = (calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) / 1000 / 60 / 60;
		// if (((calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) % (1000 * 60 * 60)) > 0) {
		// increaseDate = increaseDate + 1;
		// }
		return (int) increaseDate;
	}

	/**
	 * <p>计算两个日期之间相差多少天</p>
	 * 
	 * @param date1 起始时间
	 * @param date2 终止时间
	 */
	public static int dateDiff(final Date date1, final Date date2) throws Exception {
		Calendar calendar1 = Calendar.getInstance();
		Calendar calendar2 = Calendar.getInstance();
		calendar1.setTime(date1);
		calendar2.setTime(date2);
		long increaseDate = (calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) / 1000 / 60 / 60 / 24;
		if (((calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) % (1000 * 60 * 60 * 24)) > 0) {
			increaseDate = increaseDate + 1;
		}
		return (int) increaseDate;
	}

	/**
	 * 
	 * <p>计算两个日期之间相差月份</p>
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 * @author: 王睿磊 - nj.wangruilei@donghuienterprise.com 
	 * @date: Created on 2014-9-3 下午05:51:52
	 */
	public static int calculateMonthIn(Date date1, Date date2) {
		Calendar cal1 = new GregorianCalendar();
		cal1.setTime(date1);
		Calendar cal2 = new GregorianCalendar();
		cal2.setTime(date2);
		int c = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH)
				- cal2.get(Calendar.MONTH);
		return c;
	}

	/**
	 * <p>获得当前时间的前一个月的时间</p>
	 */
	public static Date getBeforeMonth(Date d) {
		if (d == null) {
			return null;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(d);
		calendar.add(Calendar.MONTH, -1); // 得到前一个月
		if (calendar.get(Calendar.MONTH) <= 0) {
			calendar.add(Calendar.YEAR, -1);
		}
		return calendar.getTime();
	}

	/**
	 * <p>获取某年某月的最后一天</p>
	 * 
	 * @param year 
	 * @param month 1 - 12
	 */
	public static int getLastDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);

		// 某年某月的最后一天
		return cal.getActualMaximum(Calendar.DATE);
	}

	/**
	 * <p>获取某年某月的第一天</p>
	 * 
	 * @param year
	 * @param month 1 - 12
	 */
	public static int getFirstDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);

		// 某年某月的第一天
		return cal.getActualMinimum(Calendar.DATE);
	}

	/**
	 * <p>获取某个时间的年月的字符串</p>
	 */
	public static String formatMonth(Date date) {
		if (date == null) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		try {
			return sdf.format(date);
		} catch (Exception e) {
			LOG.error(ExceptionUtils.getTrace(e));
		}
		return null;
	}

	/**
	 * <p>获取日期字符串型（当天根据天来偏移）</p>
	 */
	public static String getDateUseIntervalStr(int interval) {

		return formatDate(getDateUseInterval(interval));
	}

	/**
	 * <p>获取日期（当天根据天来偏移）</p>
	 */
	public static Date getDateUseInterval(int interval) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, interval);

		return calendar.getTime();
	}

	/**
	 * <p>获取2个日期之间的年份的列表</p>
	 */
	public static List<String> getYearListToBetweenDate(Date date1, Date date2) {
		List<String> list = new ArrayList<String>();

		Calendar calFirst = Calendar.getInstance();
		calFirst.setTime(date1);

		Calendar calSecond = Calendar.getInstance();
		calSecond.setTime(date2);

		if (calSecond.get(Calendar.YEAR) > calFirst.get(Calendar.YEAR)) {
			for (int i = calFirst.get(Calendar.YEAR); i < calSecond.get(Calendar.YEAR) + 1; i++) {
				list.add(String.valueOf(i));
			}
		} else {
			for (int i = calSecond.get(Calendar.YEAR); i < calFirst.get(Calendar.YEAR) + 1; i++) {
				list.add(String.valueOf(i));
			}
		}

		return list;
	}

	/**
	 * <p>将格式为yyyy-MM-dd时间格式化为yyyy年MM月</p>
	 */
	public static String formatYearAndMonth(Date d) {
		String yearAndMonth = new SimpleDateFormat("yyyy-MM-dd").format(d).substring(0, 7) + "月";
		yearAndMonth = yearAndMonth.replace("-", "年");
		return yearAndMonth;
	}

	/**
	 * <p>获取时间之前多少分钟的时间</p>
	 * 
	 * @param d
	 * @param interval
	 * @return
	 * @author: yy - yuyi929@gmail.com 
	 * @date: Created on 2014-1-6 下午05:04:27
	 */
	public static Date getBeforeMinutes(Date d, int interval) {
		if (d == null) {
			return null;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(d);
		calendar.add(Calendar.MINUTE, interval);
		return calendar.getTime();
	}

	/**
	 * 
	 * <p>获取所传入时间的后，mont个月的时间</p>
	 * 
	 * @param date
	 * @param mont
	 * @return
	 * @author: 虞云波 - nj.yuyunbo@donghuienterprise.com 
	 * @date: Created on 2015-3-17 下午02:04:39
	 */
	public static Date getAfterMonth(Date date, int mont) {
		if (date == null) {
			return null;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(calendar.MONTH, mont);
		return calendar.getTime();
	}

	/**
	 * <p>通过时间和增加的月份，返回新的时间</p>
	 * 
	 * @param d
	 * @param interval
	 * @return
	 * @author: yuyunbo 
	 * @date: Created on 2015-1-8 下午05:07:31
	 */
	public static Date getDateByAddMonth(Date d, int interval) {
		if (d == null) {
			return null;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(d);
		calendar.add(Calendar.MONTH, interval);
		return calendar.getTime();
	}

	/**
	 * <p>通过时间和增加的天数，返回新的时间</p>
	 * 
	 * @param d
	 * @param interval
	 * @return
	 * @author: yuyunbo 
	 * @date: Created on 2015-1-8 下午05:07:31
	 */
	public static Date getDateByAddDay(Date d, int interval) {
		if (d == null) {
			return null;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(d);
		calendar.add(Calendar.DAY_OF_MONTH, interval);
		return calendar.getTime();
	}

	/**
	 * <p>获取间隔天数的时间</p>
	 * 
	 * @param date
	 * @param days
	 * @return
	 * @author: 余毅 - yuyi@lawxp.com 
	 * @date: Created on 2016-1-7 下午03:03:15
	 */
	public static Date getAfterDays(Date date, int days) {
		if (date == null) {
			return null;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(calendar.DAY_OF_MONTH, days);
		return calendar.getTime();
	}

	/**
	 * 
	 * <p>两个日期相差为一天，或者是同一天</p>
	 * 
	 * @param firstDate
	 * @param twoDate
	 * @return
	 * @throws Exception
	 * @author: 虞云波 - yuyunbo@lawxp.com
	 * @date: Created on 2016-3-9 下午02:43:55
	 */
	public static boolean checkOverdueStartTime(Date firstDate, Date twoDate) throws Exception {

		int diffdays = dateDiff(firstDate, twoDate);

		// 在此区间标示，两个日期相差为一天，或者是同一天
		if (-1 <= diffdays && diffdays <= 1) {
			return true;
		}

		return false;
	}

	public static String getCurrentTime() {
		return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
	}

	/**
	 * 
	 * <p>将日期10号以下的补0</p>
	 * 
	 * @param dateStr
	 * @return
	 * @author: 虞云波 - yuyunbo@lawxp.com
	 * @date: Created on 2016-8-1 下午03:44:25
	 */
	public static String getDateStr(String dateStr) {

		if (StringUtils.isEmpty(dateStr)) {
			return "";
		}

		// 反斜杠替换为—
		dateStr = dateStr.replaceAll("/", "-");
		String newReturnStr = dateStr;
		String[] strArry = dateStr.split("-");
		if (strArry.length == 3) {
			// 拿到月份
			String MM = strArry[1];
			if (MM.length() == 1) {
				MM = "0" + MM;
			}
			// 拿到日期
			String dd = strArry[2];
			if (dd.length() == 1) {
				dd = "0" + dd;
			}
			newReturnStr = strArry[0] + "-" + MM + "-" + dd;
		}
		return newReturnStr;
	}

	/**
	 * 
	 * <p>根据指定时间获取前后的时间</p>
	 * 
	 * @param date
	 * @param yd
	 * @return
	 * @author: 杨辉 - 987475707@qq.com 
	 * @date: Created on 2016-11-7 上午09:36:43
	 */
	public static Date getDate(Date date, int yd) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(calendar.DATE, yd);// 正数即为把日期往后增加一天,负数往前移动
		date = calendar.getTime();
		return date;
	}

	public static void main(String[] args) throws Exception {
		// DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
		// /Calendar cal = Calendar.getInstance();
		// cal.setTime(new Date());
		// DateFormat format = new SimpleDateFormat("yyyy-MM-dd mm:hh:ss.mmm");
		// // System.out.println(format.format(getAfterMonth(new Date(),12)));
		// Calendar calendar = Calendar.getInstance();
		// calendar.set(2015, 03, 01);
		// System.out.println(format.format(calendar.getTime()));
		// System.out.println(getMonthCount(calendar.getTime()));

		// System.out.println(DateUtils.dateDiffMilliSecond(DateUtils.convertToDate("2016-08-16 11:06:00"),new Date()));
//		System.out.println(DateUtil.getDateUseIntervalStr(-2));
		
		
		
		
		System.out.println(DateUtil.dateDiffMilliSecond(new Date(Long.valueOf("1507799212435")),new Date())>5000);
		
		

		
	}

}
